package com.freight.common.core.config;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.freight.common.core.interceptor.PaginationInterceptor;
import com.freight.common.core.interceptor.QueryInterceptor;
import com.freight.common.core.interceptor.RybTenantHandler;
import com.freight.common.core.interceptor.RybTenantInterceptor;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;

@Configuration
public class MybatisPlusConfig {

    /**
     * 自定义多租户处理器
     */
    @Bean
    public RybTenantHandler bladeTenantHandler() {
        return new RybTenantHandler();
    }

    /**
     * 自定义租户拦截器
     */
    @Bean
    public RybTenantInterceptor tenantLineInnerInterceptor(RybTenantHandler tenantHandler) {
        RybTenantInterceptor tenantInterceptor = new RybTenantInterceptor();
        tenantInterceptor.setTenantLineHandler(tenantHandler);
        return tenantInterceptor;
    }

    /**
     * mybatis-plus 拦截器集合
     */
    @Bean
    @ConditionalOnMissingBean(MybatisPlusInterceptor.class)
    public MybatisPlusInterceptor mybatisPlusInterceptor(ObjectProvider<QueryInterceptor[]> queryInterceptors, RybTenantInterceptor tenantInterceptor) {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 配置租户拦截器
        interceptor.addInnerInterceptor(tenantInterceptor);
        // 配置分页拦截器
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        // 配置自定义查询拦截器
        QueryInterceptor[] queryInterceptorArray = queryInterceptors.getIfAvailable();
        if (ObjectUtil.isNotEmpty(queryInterceptorArray)) {
            AnnotationAwareOrderComparator.sort(queryInterceptorArray);
            paginationInterceptor.setQueryInterceptors(queryInterceptorArray);
        }
//        paginationInterceptor.setMaxLimit(mybatisPlusProperties.getPageLimit());
//        paginationInterceptor.setOverflow(mybatisPlusProperties.getOverflow());
        interceptor.addInnerInterceptor(paginationInterceptor);
        return interceptor;
    }

    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return configuration -> configuration.setUseDeprecatedExecutor(false);
    }

}
